import { resourceEntApi } from '@/api';
import { OSSDIR, pageOpeTypeEnum } from '@/common';
import YmCollaPanes from '@/components/YmCollaPanes';
import { YmRichEditor } from '@/components/YmRichEditor';
import { useAppSelector } from '@/redux/store';
import { Button, Col, Form, Input, message, Row } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { v4 as uuid } from 'uuid';
import { useYmAliOss, YmAddPageLayout, YmUpload, type YmAddPageLayoutProps } from 'ym-design';

const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};
const { PaneItem } = YmAddPageLayout;

const plantType = process.env.processEnvDetail.REACT_APP_PLATFORM;
function AddGraphicCourseWare() {
  const [searchParam] = useSearchParams();
  const navigator = useNavigate();
  const type = searchParam.get('type');
  const parentId = searchParam.get('parentId');
  const { entId } = useAppSelector((state) => state.loginEnt);
  const coursewareId = searchParam.get('resourceId');
  const [form] = Form.useForm();
  const [loadingDetail, setLoadingDetail] = useState({
    subBtnDis: false,
    viewLoading: false,
  });

  // 使用aliyunoss进行操作
  const customRequest = useYmAliOss();

  useEffect(() => {
    if (type === pageOpeTypeEnum['edit']) {
      resourceEntApi.getCourseWareById({ coursewareId }).then((res: any) => {
        const {
          data: { name, picUrl, picTextContent },
        } = res;
        form.setFieldsValue({ name, picUrl: [{ uid: uuid(), url: picUrl }], pictextContent: picTextContent });
      });
    }
  }, [coursewareId, form, type]);

  const goBackToList = () => {
    const x = plantType === 'boss' ? '/resourceLibrary/' : '/cusResLib/';
    navigator(x + 'courseWare', { state: { activeTab: 'graphicCourseWare' } });
  };

  const _formSub = (subType: number) => {
    setLoadingDetail({ subBtnDis: true, viewLoading: true });
    form
      .validateFields()
      .then((values) => {
        const { name, picUrl, pictextContent } = values;
        let newText = pictextContent;
        newText = newText.replaceAll('style=""', 'style="max-width: 100%"');
        const subData: any = {
          type: '200',
          picTextContent: newText,
          entId,
          name,
          picUrl: picUrl[0].response,
          parentId,
          // pictextContent,
          // coursewareType: 'txt',
        };
        // console.log('--addGraphicCourseWare--subData--:', subData);
        let requestApi;
        if (type === pageOpeTypeEnum['add']) {
          requestApi = resourceEntApi.createCourseWare(subData);
        } else if (type === pageOpeTypeEnum['edit']) {
          if (plantType === 'boss') subData.coursewareId = coursewareId;
          else subData.guid = coursewareId;
          requestApi = resourceEntApi.updateCourseWare(subData);
        } else {
          return message.error('type 未定义');
        }
        requestApi
          .then((res: any) => {
            const { code, msg } = res;
            if (code === '200') {
              message.success(msg || `${type === pageOpeTypeEnum['add'] ? '添加' : '编辑'}成功`);
              if (subType === 1) {
                //保存
                goBackToList();
              } else {
                //保存并继续
                form.resetFields();
              }
            } else {
              message.error(msg);
            }
          })
          .catch((err: any) => {
            console.log('--addGraphicCourseWare--_formSub--err--:', err);
          })
          .finally(() => {
            setLoadingDetail({ subBtnDis: false, viewLoading: false });
          });
      })
      .catch((err) => {
        setLoadingDetail({ subBtnDis: false, viewLoading: false });
      });
  };
  // 保存
  const sub = () => {
    _formSub(1);
  };

  // 保存并继续添加
  const subAndContinue = () => {
    _formSub(2);
  };

  const operationFooter = useMemo(() => {
    const operationBtn = [
      <Button key="subOnce" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={sub}>
        保存
      </Button>,
      <Button key="subContinue" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={subAndContinue}>
        保存并继续添加
      </Button>,
    ];
    switch (type) {
      case pageOpeTypeEnum['add']:
        return operationBtn;
      case pageOpeTypeEnum['edit']:
        return operationBtn.slice(0, 1); //substring from to
    }
  }, [type, loadingDetail]);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          goBackToList();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );

  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem
        tabKey="tab1"
        label={(type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + '图文课件'}
        className="pane_tab1"
      >
        <YmCollaPanes collapsible={false} headerTitle={<div></div>} paneKey={1} collPanesActiveKeys={[1]}>
          <Form layout="horizontal" labelAlign="right" size="middle" form={form}>
            <Row>
              <Col span={24}>
                <Form.Item label="封面图" required>
                  <Form.Item name="picUrl" noStyle rules={YmUpload.formRules('请上传课件封面图')}>
                    <YmUpload
                      maxCount={1}
                      cardWidth={140}
                      cardHeight={140}
                      accept="image/*"
                      customRequest={customRequest}
                    >
                      上传图片
                    </YmUpload>
                  </Form.Item>
                  <p className="safe-edu_upload_warning">图片宽高比例以1.875:1为宜，如：750*400</p>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item name="name" label="名称" rules={requireRules('请输入课件名称')}>
                  <Input
                    placeholder="请输入"
                    autoComplete="off"
                    maxLength={18}
                    showCount
                    style={{ maxWidth: '300px' }}
                  />
                </Form.Item>
              </Col>
              <Col span={24} style={{ marginBottom: 20 }}>
                <Form.Item name="pictextContent" label="内容" rules={requireRules('请上传课件内容')}>
                  <YmRichEditor
                    fileUploadConfig={{ dir: OSSDIR }}
                    editorStyle={{ height: '370px', overflowY: 'auto' }}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </YmCollaPanes>
      </PaneItem>
    </YmAddPageLayout>
  );
}

export default AddGraphicCourseWare;
